package banner

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetBannerListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetBannerListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetBannerListLogic {
	return &BackendGetBannerListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendGetBannerListLogic) BackendGetBannerList(in *backend.BannerListReq) (*backend.BannerListResp, error) {
	// logx.Infof("BackendGetBannerList : %+v ", in)

	var orderBys []string
	if len(in.OrderBy) > 0 {
		for _, orderBy := range in.OrderBy {
			order := " ASC"
			if orderBy.Order == "1" {
				order = " DESC"
			}
			if orderBy.Field == "id" {
				orderBys = append(orderBys, model.BannerColumns.ID+order)
			}
			if orderBy.Field == "sort" {
				orderBys = append(orderBys, model.BannerColumns.Sort+order)
			}
			if orderBy.Field == "createdAt" {
				orderBys = append(orderBys, model.BannerColumns.CreatedAt+order)
			}
		}
	}

	var stati string
	var bannerType string
	if len(in.FilterBy) > 0 {
		for _, filterBy := range in.FilterBy {
			switch filterBy.Field {
			case "status":
				stati = filterBy.In
			case "type":
				bannerType = filterBy.In
			}
		}
	}

	var page uint64
	var pageSize uint64
	var restricted bool
	var withCount int
	var preCount int64
	filterMap := make(map[string]map[string][]any)
	resp := &backend.BannerListResp{}
	if in.Ids != nil && len(*in.Ids) > 0 {
		if vals := modelx.UniqueInterfaces(*in.Ids, 64); len(vals) == 0 {
			return resp, nil
		} else {
			filterMap[model.BannerColumns.ID] = map[string][]any{
				"in": vals,
			}
			restricted = true
			withCount = -1
			preCount = int64(len(vals))
		}
	}

	var statusIsSet bool
	var isAll bool
	statusMap := make(map[string][]any)
	switch bannerType {
	case "1": // 全部
		statusMap["notEqualTo"] = []any{globalkey.PostStatusTrash}
		isAll = true
	case "2": // 正常
		filterMap[model.BannerColumns.Status] = map[string][]any{
			"equalTo": {globalkey.StatusNormal},
		}
		statusIsSet = true
	case "3": // 禁用
		filterMap[model.BannerColumns.Status] = map[string][]any{
			"equalTo": {globalkey.StatusBanned},
		}
		statusIsSet = true
	case "4": // 回收站
		filterMap[model.BannerColumns.Status] = map[string][]any{
			"equalTo": {globalkey.StatusDeleted},
		}
		statusIsSet = true
	}

	if !restricted {
		page = in.Page
		pageSize = in.PageSize
		withCount = 1
	}

	if in.Type != nil {
		filterMap[model.BannerColumns.Type] = map[string][]any{
			"equalTo": {*in.Type},
		}
	}
	if in.Title != nil {
		filterMap[model.BannerColumns.Title] = map[string][]any{
			"contain": {*in.Title},
		}
	}

	var startTimeIn []any
	var endTimeIn []any
	if in.StartTime != nil && len(strings.TrimSpace(*in.StartTime)) > 0 {
		if startTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.StartTime)); err == nil {
			startTimeIn = append(startTimeIn, startTime)
		}
	}
	if in.EndTime != nil && len(strings.TrimSpace(*in.EndTime)) > 0 {
		if endTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.EndTime)); err == nil {
			endTimeIn = append(endTimeIn, endTime)
		}
	}
	createdAtMap := make(map[string][]any)
	if len(startTimeIn) > 0 {
		createdAtMap["moreThanOrEqualTo"] = startTimeIn
	}
	if len(endTimeIn) > 0 {
		createdAtMap["lessThan"] = endTimeIn
	}
	filterMap[model.BannerColumns.CreatedAt] = createdAtMap

	if isAll {
		ret, _, err := l.svcCtx.Banner.GetList(l.ctx, model.M{
			"statistic": "1",
		}, 5, filterMap)
		if err != nil {
			// return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			logx.Errorw("BackendGetBannerList GetList statistic err", logx.Field("detail", err.Error()))
		} else if len(ret) > 0 {
			statusStatisticMap := make(map[uint32]uint32)
			var total uint16
			for _, v := range ret {
				total += v.Sort
				statusStatisticMap[uint32(v.Status)] = uint32(v.Sort)
			}
			statusStatisticMap[uint32(4)] = uint32(total)
			resp.StatusStatisticMap = statusStatisticMap
		}
	}

	if !statusIsSet {
		statusIn := modelx.UniqueInterfaces(stati, 32)
		if len(statusIn) > 0 {
			statusMap["in"] = statusIn
		}
		if in.Status != nil {
			statusMap["equalTo"] = []any{*in.Status}
		}
		filterMap[model.BannerColumns.Status] = statusMap
	}

	var orderBy string
	if len(orderBys) > 0 {
		orderBy = strings.Join(orderBys, ",")
	}

	res, count, err := l.svcCtx.Banner.GetList(l.ctx, model.M{
		"page":     page,
		"pageSize": pageSize,
		"orderBy":  orderBy,
	}, withCount, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if restricted {
		count = preCount
	}
	resp.Total = uint64(count)

	if len(res) > 0 {
		var bids []any
		for _, v := range res {
			bids = append(bids, v.ID)
		}

		mediaFilterMap := make(map[string]map[string][]any)
		mediaFilterMap[model.AttachmentRelationshipColumns.ObjectID] = map[string][]any{
			"in": bids,
		}
		mediaFilterMap[model.AttachmentRelationshipColumns.ObjectType] = map[string][]any{
			"equalTo": {globalkey.AttachmentLogTypeBanner},
		}
		mediaList, _, err := l.svcCtx.Banner.GetMedia(l.ctx, model.M{}, -1, mediaFilterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		idMediaMap := make(map[uint64][]*backend.MediaInfo)
		if len(mediaList) > 0 {
			for _, v := range mediaList {
				idMediaMap[v.ObjectID] = append(idMediaMap[v.ObjectID], &backend.MediaInfo{
					Uid:       &v.RelationshipID,
					Id:        pointy.GetPointer(strconv.FormatInt(int64(v.AttachmentID), 10)),
					Thumbnail: pointy.GetPointer(uint32(v.AttachmentThumbnail)),
					Order:     pointy.GetPointer(uint32(v.AttachmentOrder)),
					Uri:       &v.AttachmentImageSource,
					Url:       &v.AttachmentImageURL,
					AltText:   &v.AttachmentImageAlt,
					MetaData:  &v.AttachmentImageMeta,
				})
			}
		}

		for _, v := range res {
			var media []*backend.MediaInfo
			if ms, ok := idMediaMap[v.ID]; ok {
				media = ms[:]
			}
			var sort *uint32
			if v.Sort != uint16(globalkey.SystemDefaultSort) {
				sort = pointy.GetPointer(uint32(v.Sort))
			}
			resp.List = append(resp.List, &backend.BannerInfo{
				Id:        &v.ID,
				PicId:     &v.PicID,
				PicUrl:    &v.PicURL,
				Type:      pointy.GetPointer(uint32(v.Type)),
				Title:     &v.Title,
				LinkType:  pointy.GetPointer(uint32(v.LinkType)),
				LinkUrl:   &v.LinkURL,
				AdType:    pointy.GetPointer(uint32(v.ObjectType)),
				AdId:      &v.ObjectID,
				Status:    pointy.GetPointer(uint32(v.Status)),
				Sort:      sort,
				CreatedAt: pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
				UpdatedAt: pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
				DeletedAt: pointy.GetPointer(modelx.FormatNullDotTime(v.DeletedAt, "")),
				StartedAt: pointy.GetPointer(modelx.FormatNullDotTime(v.StartedAt, "")),
				EndedAt:   pointy.GetPointer(modelx.FormatNullDotTime(v.EndedAt, "")),
				Media:     media,
			})
		}
	}

	return resp, nil
}
